import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) {
		if (args.length != 1) {
			System.out.println("Usage: java Server <port>");
			System.exit(-1);
		}
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		DataInputStream inputStream = null;
		FileOutputStream outputStream = null;
		int counter = 1;
		int bufferLength = 256;
		byte[] buffer = new byte[bufferLength];
		try {
			serverSocket = new ServerSocket(Integer.parseInt(args[0]));
			while (true) {
				clientSocket = serverSocket.accept();
				System.out.println("Opening file: outputFile" + counter);
				inputStream = new DataInputStream(clientSocket.getInputStream());
				outputStream = new FileOutputStream("outputFile" + counter);
				int readLength;
				System.out.println("Writing to file...");
				while ((readLength = inputStream.read(buffer)) > 0) {
					outputStream.write(buffer, 0, readLength);
				}
				System.out.println("Finished writing!");
				clientSocket.close();
				outputStream.close();
				counter++;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (clientSocket != null) {
				try {
					clientSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
